//
//  EMSetQuestionViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/25.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMSetQuestionViewController.h"
#import "EMInputTextField.h"
#import "UINavigationController+EMNavi.h"
#import "EMActionSheet.h"
#import "EMGetQuestionsReqBody.h"
#import "EMGetQuestionsRespBody.h"
#import "EMSetQuestionsReqBody.h"
#import "EMSetQuestionsRespBody.h"
#import "MBProgressHUD.h"
#import "AppDelegate.h"
#import "UserInfo.h"
@interface EMSetQuestionViewController ()
{
    EMInputTextField *answer1TF;
    EMInputTextField *answer2TF;
    EMInputTextField *answer3TF;
    
    AppDelegate *app;
    EMActionSheet *actionSheet;
    NSMutableDictionary *questionDictionary;
    NSArray *questionBtnArray;
    
    UIButton *question1Btn;
    UIButton *question2Btn;
    UIButton *question3Btn;
    
    UIButton *senderBtn;
}
@end

@implementation EMSetQuestionViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = RGB(242, 242, 242);
    
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"设置安全问题";
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
    
    
}
- (void)backAction: (UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   // questionArray = @[@"请问您的班主任号码是多少呢", @"请问您的门牌号是多少呢", @"请问您的左手手指有多长", @"请问您多少斤", @"请问你上星期六下午三点在干什么", @"请问离你最近的一辆汽车的车牌号多少", @"请问您来自哪个星球"];
    UIImage *arrow = [UIImage imageNamed:@"icon_菜单_展开"];
    questionDictionary = [[NSMutableDictionary alloc] init];
    [self getQuestions];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    scrollView.contentSize = CGSizeMake(W(320), H(800));
    
    int height = 25;
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(20))];
    tipLabel.text = @"请设置3个安全认证问题";
    tipLabel.textColor = [UIColor darkGrayColor];
    tipLabel.textAlignment = NSTextAlignmentLeft;
    tipLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [scrollView addSubview:tipLabel];
    height += 20 + 10;
    question1Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    question1Btn.frame = CGRectMake(W(10), H(height), W(300), H(35));
    question1Btn.layer.borderColor = RGB(112, 179, 81).CGColor;
    question1Btn.layer.borderWidth = 1;
    question1Btn.layer.cornerRadius = 5;
    question1Btn.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    question1Btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    question1Btn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    [question1Btn setTitle:questionDictionary[@"1"] forState:UIControlStateNormal];
    [question1Btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    question1Btn.tag = 1691;
    
    UIButton *but1 = [UIButton buttonWithType:UIButtonTypeSystem];
    but1.frame = CGRectMake(question1Btn.frame.size.width - W(35), 0, W(35), H(35));
    
    [but1 setImage:[arrow imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    but1.layer.borderColor = RGB(112, 179, 81).CGColor;
    but1.layer.borderWidth = 1;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:but1.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = but1.bounds;
    maskLayer.path = maskPath.CGPath;
    but1.layer.mask = maskLayer;
    [question1Btn addSubview:but1];
    [question1Btn addTarget:self action:@selector(chooseQuestion:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:question1Btn];
    
    height += 30 + 15;
    answer1TF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    answer1TF.placeholderText = @"请输入答案";
    [answer1TF setTextFieldMode:EMInputTextFieldModeText];
    answer1TF.inputTextField.delegate = self;
    [scrollView addSubview:answer1TF];
    
    height += 30 + 20;
    question2Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    question2Btn.frame = CGRectMake(W(10), H(height), W(300), H(35));
    question2Btn.layer.borderColor = RGB(112, 179, 81).CGColor;
    question2Btn.layer.borderWidth = 1;
    question2Btn.layer.cornerRadius = 5;
    question2Btn.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    question2Btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    question2Btn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    [question2Btn setTitle:questionDictionary[@"2"]  forState:UIControlStateNormal];
    [question2Btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    question2Btn.tag = 1692;
    UIButton *but2 = [UIButton buttonWithType:UIButtonTypeSystem];
    but2.frame = CGRectMake(question2Btn.frame.size.width - W(35), 0, W(35), H(35));
    [but2 setImage:[arrow imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    but2.layer.borderColor = RGB(112, 179, 81).CGColor;
    but2.layer.borderWidth = 1;
    UIBezierPath *maskPath2 = [UIBezierPath bezierPathWithRoundedRect:but2.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer2 = [[CAShapeLayer alloc] init];
    maskLayer2.frame = but2.bounds;
    maskLayer2.path = maskPath2.CGPath;
    but2.layer.mask = maskLayer2;
    [question2Btn addSubview:but2];
    [question2Btn addTarget:self action:@selector(chooseQuestion:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:question2Btn];
    
    height += 30 + 15;
    answer2TF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    answer2TF.placeholderText = @"请输入答案";
    [answer2TF setTextFieldMode:EMInputTextFieldModeText];
    answer2TF.inputTextField.delegate = self;
    [scrollView addSubview:answer2TF];
    
    height += 30 + 20;
    question3Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    question3Btn.frame = CGRectMake(W(10), H(height), W(300), H(35));
    question3Btn.layer.borderColor = RGB(112, 179, 81).CGColor;
    question3Btn.layer.borderWidth = 1;
    question3Btn.layer.cornerRadius = 5;
    question3Btn.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    question3Btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    question3Btn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    [question3Btn setTitle:questionDictionary[@"3"]  forState:UIControlStateNormal];
    [question3Btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    question3Btn.tag = 1693;
    UIButton *but3 = [UIButton buttonWithType:UIButtonTypeSystem];
    but3.frame = CGRectMake(question3Btn.frame.size.width - W(35), 0, W(35), H(35));
    [but3 setImage:[arrow imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    but3.layer.borderColor = RGB(112, 179, 81).CGColor;
    but3.layer.borderWidth = 1;
    UIBezierPath *maskPath3 = [UIBezierPath bezierPathWithRoundedRect:but3.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer3 = [[CAShapeLayer alloc] init];
    maskLayer3.frame = but3.bounds;
    maskLayer3.path = maskPath3.CGPath;
    but3.layer.mask = maskLayer3;
    [question3Btn addSubview:but3];
    [question3Btn addTarget:self action:@selector(chooseQuestion:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:question3Btn];
    
    height += 30 + 15;
    answer3TF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    answer3TF.placeholderText = @"请输入答案";
    [answer3TF setTextFieldMode:EMInputTextFieldModeText];
    answer3TF.inputTextField.delegate = self;
    [scrollView addSubview:answer3TF];
    
    questionBtnArray = @[question1Btn, question2Btn, question3Btn];
    
    height += 30 + 30;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(W(10), H(height), W(300), H(40));
    btn.backgroundColor = RGB(112, 179, 81);
    btn.layer.cornerRadius = 5;
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [btn setTitle:@"确认提交" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(handupQuestion:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:btn];
    
    [self.view addSubview:scrollView];
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackground:)];
    [self.view addGestureRecognizer:tapGR];
    
    UITableView *questionTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 290, 216) style:UITableViewStylePlain];
    questionTable.delegate = self;
    questionTable.dataSource = self;
    questionTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    questionTable.backgroundColor = [UIColor clearColor];
    questionTable.showsVerticalScrollIndicator = NO;
    actionSheet =[[EMActionSheet alloc]initWithFrame:CGRectMake(0,[UIScreen mainScreen].bounds.size.height , [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [actionSheet initWithTitle:@"查询类型" andContentView:questionTable];
    
}

- (void)chooseQuestion:(UIButton *)sender
{
    [UIView animateWithDuration:0.3 animations:^{
        actionSheet.frame =CGRectMake(0,0 ,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        [self.navigationController.view addSubview:actionSheet];
    }];
    senderBtn = sender;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return questionDictionary.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"quesCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    UILabel *questionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, H(5), W(290), H(50))];
    questionLabel.layer.cornerRadius = 10;
    questionLabel.layer.backgroundColor = RGB(117, 179, 81).CGColor;
    questionLabel.numberOfLines = 0;
    questionLabel.textColor = RGB(242, 242, 242);
    questionLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    NSArray *qArr = [questionDictionary allValues];
    questionLabel.text = qArr[indexPath.row];
    [cell addSubview:questionLabel];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return H(60);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *qArr = [questionDictionary allValues];
    [senderBtn setTitle:qArr[indexPath.row] forState:UIControlStateNormal];
    [actionSheet removeActionSheet];
}

#pragma mark - 关闭键盘
- (void)tapBackground:(UIGestureRecognizer *)recog
{
    [self closeKeyboard];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self closeKeyboard];
    return NO;
}

- (void)closeKeyboard
{
    [answer1TF.inputTextField resignFirstResponder];
    [answer2TF.inputTextField resignFirstResponder];
    [answer3TF.inputTextField resignFirstResponder];
}
#pragma mark - 点击事件
- (void)handupQuestion:(UIButton *)sender
{
    
    NSLog(@"%@", question1Btn.titleLabel.text);
    NSString *k1 = [questionDictionary allKeysForObject:question1Btn.titleLabel.text][0];
    NSString *a1;
    if (answer1TF.inputTextField.text.length == 0 || [answer1TF.inputTextField.text isEqualToString:@""]) {
        [app showTip:@"请填写答案"];
        return;
    } else {
        a1 = answer1TF.inputTextField.text;
    }
    
    NSString *k2 = [questionDictionary allKeysForObject:question2Btn.titleLabel.text][0];
    NSString *a2;
    if (answer2TF.inputTextField.text.length == 0 || [answer2TF.inputTextField.text isEqualToString:@""]) {
        [app showTip:@"请填写答案"];
        return;
    } else {
        a2 = answer2TF.inputTextField.text;
    }
    
    NSString *k3 = [questionDictionary allKeysForObject:question3Btn.titleLabel.text][0];
    NSString *a3;
    if (answer3TF.inputTextField.text.length == 0 || [answer3TF.inputTextField.text isEqualToString:@""]) {
        [app showTip:@"请填写答案"];
        return;
    } else {
        a3 = answer3TF.inputTextField.text;
    }
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMSetQuestionsReqBody *reqBody = [[EMSetQuestionsReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"SET-PASSWORD-PROBLEM";
    reqBody.UID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.PROBLEM = @[@{@"id":k1, @"answer":a1}, @{@"id":k2, @"answer":a2}, @{@"id":k3, @"answer":a3}];
 
    
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMSetQuestionsRespBody *respBody = [EMSetQuestionsRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            [app showTip:respBody.SUCCESSFULINFO];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

    
}
- (void)showAlert:(NSString *)content
{
    EMAttention *attention = [[EMAttention alloc] initWithTitle:@"提示" contentText:content leftButtonTitle:nil rightButtonTitle:@"确定"];
    [attention show];
}

#pragma -
- (void)getQuestions
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMGetQuestionsReqBody *reqBody = [[EMGetQuestionsReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"MODIFY-PASSWORD-PROBLEM";

    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMGetQuestionsRespBody *respBody = [EMGetQuestionsRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            for (int i = 0; i < respBody.SUCCESSFULINFO.count; i ++) {
                NSArray *qInfo = respBody.SUCCESSFULINFO[i];
                [questionDictionary setObject:qInfo[1] forKey:qInfo[0]];
            }
            
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
}
@end
